import React from 'react'
import { FlatList } from 'react-native'
import { connect } from 'react-redux' // 引入connect函数
import ItemImage from '../../../../../components/list/articleItem'
import Page from '../../../../../libs/page'
import ListEmpty from '../../../../../components/listEmpty'
const ITEM_HEIGHT = 100

const apiUrl = '/api/article/list'
class List extends React.Component {
	constructor() {
		super()
		this.state = {
			pageManager: {},
			list: [],
			refreshing: false
		}
	}

	componentDidMount() {
		this.startPage()
	}

	async startPage() {
		let { id } = this.props.curItem
		if (id) {
			// 查询文章列表
			let pageManager = new Page({
				apiUrl: apiUrl,
				dataKey: 'data.list',
				params: {
					id
				}
			})
			let list = await pageManager.start()
			this.setState({
				pageManager,
				list
			})
		}
	}

	// 下拉刷新

	// 加载更多
	async _onEndReached() {
		let list = await this.state.pageManager.next()
		this.setState({
			list
		})
	}

	renderItem = ({ item }) => {
		let { money } = this.props.curItem
		return <ItemImage key={item.id} info={item} money={money || '0.00'} />
	}

	async _onRefresh() {
		let list = await this.state.pageManager.start()
		this.setState({
			list
		})
	}

	render() {
		let { list, refreshing } = this.state
		return (
			<FlatList
				data={list}
				ListEmptyComponent={ListEmpty}
				renderItem={this.renderItem}
				keyExtractor={item => item.name}
				refreshing={refreshing}
				onRefresh={this._onRefresh.bind(this)}
				onEndReachedThreshold={0.1}
				onEndReached={this._onEndReached.bind(this)}
				getItemLayout={(data, index) => ({
					length: ITEM_HEIGHT,
					offset: (ITEM_HEIGHT + 2) * index,
					index
				})}
				// onViewableItemsChanged={info => {
				//   alert('可见不可见触发')
				// }}
				style={{ paddingTop: 10 }}
			/>
		)
	}
}

export default connect(state => ({
	curTypeItem: state.article.curTypeItem
}))(List)
